import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

import com.speljohan.rsbot.event.events.*;
import com.speljohan.rsbot.event.listeners.*;
import com.speljohan.rsbot.accessors.*;
import com.speljohan.rsbot.account.*;
import com.speljohan.rsbot.bot.*;
import com.speljohan.rsbot.script.wrappers.*;
import com.speljohan.rsbot.script.*;
import com.speljohan.rsbot.bot.Bot;
import com.speljohan.rsbot.event.listeners.*;

public class RedChinchompaCatcher extends Script implements PaintListener, ServerMessageListener {
	public int redChinID=5080;
	public int redChinInvID=10034;
	public int boxID=10008;
	public int setupBoxID=19187;
	public int failedTrapID=19192;
	public int successfulTrapID=19190;
	public int failingTrapID=19188;
	public int setupAnimation=5208;
	public int pickupAnimation=5212;
	public int[] successingTrapID={19197, 19198, 19199, 19200};
	public RSTile[] spawnLocations={new RSTile(2553,2935), new RSTile(2557, 2932), new RSTile(2557,2936), new RSTile(2508, 2909), new RSTile(2506, 2906), new RSTile(2525, 2895)};
	public RSTile[] boxLocations= new RSTile[5];
	public RSTile[] boxLocations2= new RSTile[4];
	public int spawnChoice;
	public boolean autoUpdate;
	public int currentLevel;
	public int[] Inventory=new int[28];
	public RSObject tileObjects;
	public int startXP = skills.getCurrentSkillExp(STAT_HUNTER);
	public int gainedXP=0;
	public int startLevel = skills.getCurrentSkillLevel(STAT_HUNTER);
	public int caughtChins=0;
	public String charStatus="Loading...";
	public long runTime=0;
	public int antiBanChins=0;
	public String locationChoice;
	
    /*******************************
     * Thanks to Drizzt1112's Swamp Lizard Hunter script
     * for this function. It is very useful!
     * @param RSTile
     * @param action
     * @return
     *******************************/
    public boolean atTileTake(RSTile tile, String action) {
		int TempCounter = 0;
		while (true) {
			if (!getMyPlayer().isMoving()) break;
			wait(random(50, 100));
		}
		try {
			Point location = Calculations.tileToScreen(tile);
			if (location.x == -1 || location.y == -1) return false;
			moveMouse(location, 8,8);
			wait(random(50, 100));
			while(!getMenuItems().get(0).toLowerCase().contains(action.toLowerCase()) && TempCounter < 5){
			location = Calculations.tileToScreen(tile);
			moveMouse(location, 8,8);
			TempCounter++;
			}
			if(getMenuItems().get(0).toLowerCase().contains(action.toLowerCase())) {
			clickMouse(true);
			}
			else {
			clickMouse(false);
			atMenu(action);
			}
			wait(random(50, 100));
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	public void checkUpdate(){
		if(getOVersion()>getVersion())
			log("Update Available! Version " + getOVersion() + " Released!");
		else
			log("No Update Available.");
		return;
	}
    public boolean clickcontinue() {
        if(getContinueChildInterface() != null) {
            if(getContinueChildInterface().getText().contains("to continue")) {
                return atInterface(getContinueChildInterface());
            }
        }    
        return false;    
    }
	public String getName(){return "Red Chinchompa Catcher";}
	public String getAuthor(){return "Marneus901";}
	public String getScriptCategory(){return "Hunter";}
	public double getVersion(){return 0.7;}
	public static double getOVersion() {
		try {
			URL url = new URL("http://circadian.20fr.com/RedChinnerVersion.txt");
			BufferedReader br = new BufferedReader(new InputStreamReader(
					new BufferedInputStream(url.openConnection().getInputStream())));
			double ver = Double.parseDouble(br.readLine().trim());
			br.close();
			return ver;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
    public String getScriptDescription( ) {
        String html = "<html>";
        html += "<head>";
        html += "<style type=\"text/css\"> hr {color: white} p {margin-left: 20px}</style>";
        html += "</head>";
        html += "<body>";
        html += "<center>";
        html += "<b><font size=\"4\" color=\"red\">" + getName() + " v" + getVersion() + "</font></b><br>";
        html += "</center>";
        html += "<center><table border=\"0\"><tr><center><td colspan=\"2\"><font size=\"4\"><b>:: Script Settings ::</b></font><BR><font size=\"2\" color=\"red\">Thanks to Aelin for this script setup screen!</font></td></center></tr><tr><td colspan=\"2\"><hr></td></tr><tr><td>";
        html += "<center><tr><td colspan=\"2\"><font size=\"4\" color=\"blue\">Start at the Feldip Red Chinchompa hunting spot.<BR></font></center></td></tr>";
        html += "<tr><td><b>Chinchompa Spawn Location: </b></td><td><center><select name=\"locationName\">";
        html += "<option>2553, 2935";
        html += "<option>2557, 2932";
        html += "<option>2557, 2936";
        html += "<option>2508, 2909";
        html += "<option>2506, 2906";
        html += "<option>2525, 2895";
        html +="</select></center></td></tr>";
        html += "<tr><td><b>Check for updates : </b></td><td><input type=\"checkbox\" name=\"updates\" value=\"true\"></center></td></tr>";
        html += "</table>";
        html += "</center></body>";
        html += "</html>";
        return html;
    }
	public void ifLost(){
		if(getMyPlayer().getLocation().getX()<spawnLocations[spawnChoice].getX()-2 ||
				getMyPlayer().getLocation().getX()>spawnLocations[spawnChoice].getX()+1 ||
				getMyPlayer().getLocation().getY()<spawnLocations[spawnChoice].getY()-1 ||
				getMyPlayer().getLocation().getY()>spawnLocations[spawnChoice].getY()+1){
			//Find a way to teleport to CW then walk back
			if(!walkTileMM(spawnLocations[spawnChoice])){
				log("Were are not at the Red Chinchompa hunting spot.");
				stopAllScripts();
			}
		}
	}
	public boolean isWelcomeButton()
	{		
		RSInterface welcomeInterface = RSInterface.getInterface(378);
        if(welcomeInterface.getChild(45).getAbsoluteX() > 20 || (!welcomeInterface.getChild(117).getText().equals("10.1120.190") && !welcomeInterface.getChild(117).getText().equals(""))) { 
			log("We still are in Welcome Screen");
			return true;	
		} else {
			return false;
		}	
	}
    public void onFinish(){
    	Bot.getEventManager().removeListener(PaintListener.class, this);
    	Bot.getEventManager().removeListener(ServerMessageListener.class, this);
        return;
    }
	public void onRepaint(Graphics g) {
		int X = 310;
		int Y = 5;
		long millis = System.currentTimeMillis() - runTime;
		long hours = millis / (1000 * 60 * 60);
		millis -= hours * (1000 * 60 * 60);
		long minutes = millis / (1000 * 60);
		millis -= minutes * (1000 * 60);
		long seconds = millis / 1000;
		if (isLoggedIn()) {
			g.setColor(new Color(0, 255, 0, 50));
			g.drawRoundRect(X, Y, 205, 155, 20, 20);
			Y+=15;
			X+=5;
			g.setColor(Color.YELLOW);
			g.drawString("RedChin Catcher v"+getVersion()+" - "+getAuthor(), X, Y);
			Y+=15;
			g.drawString("Status : " + charStatus, X, Y);
			Y+=15;
			g.drawString("Runtime : " + hours + ":" + minutes + ":" + seconds, X, Y);
			Y+=15;
			g.drawString("Chinchompas Caught : " + caughtChins, X, Y);
			Y+=15;
			g.drawString("XP Gain : " + caughtChins*265, X, Y);
			Y+=15;
			g.drawString("XP until level : " + skills.getXPToNextLevel(STAT_HUNTER), X, Y);
			Y+=15;
			g.drawString("Levels Gained : " + (skills.getCurrentSkillLevel(STAT_HUNTER)-startLevel), X, Y);
			Y+=15;
			long aminutes=minutes+(hours*60);
			if(caughtChins>0 && aminutes>0){
				g.drawString("Experience Per Hour : " + ((caughtChins*265)/aminutes)*60, X, Y);
				Y+=15;
				g.drawString("Chins Per Hour : " + ((caughtChins)/aminutes)*60, X, Y);
				Y+=15;
				g.drawString("Time Till Levelup : " + skills.getXPToNextLevel(STAT_HUNTER)/((caughtChins*265)/aminutes) + "min", X, Y);
			}
		}
	}
	public boolean onStart(Map<String, String> args) {
		runTime=System.currentTimeMillis();
		locationChoice=args.get("locationName");
		if(locationChoice.equals("2553, 2935"))
			spawnChoice=0;
		if(locationChoice.equals("2557, 2932"))
			spawnChoice=1;
		if(locationChoice.equals("2557, 2936"))
			spawnChoice=2;
		if(locationChoice.equals("2508, 2909"))
			spawnChoice=3;
		if(locationChoice.equals("2506, 2906"))
			spawnChoice=4;
		if(locationChoice.equals("2525, 2895"))
			spawnChoice=5;
		setCords();
		autoUpdate = args.get("update") != null ? true : false;
		if(autoUpdate)checkUpdate();
		return true;
    }
	public void serverMessageRecieved(ServerMessageEvent e) {
		String message = e.getMessage();
		if(message.contains("You've caught a carnivorous chinchompa.")){
			caughtChins++;
			antiBanChins++;
		}
	}
    /*******************************
     * Sets up the RSTiles that will be used
     * for setting up box traps
     */
    public void setCords(){
    	boxLocations= new RSTile[]{new RSTile(spawnLocations[spawnChoice].getX()-1,spawnLocations[spawnChoice].getY()-1),
    			new RSTile(spawnLocations[spawnChoice].getX()+1,spawnLocations[spawnChoice].getY()-1),
    			new RSTile(spawnLocations[spawnChoice].getX(),spawnLocations[spawnChoice].getY()),
    			new RSTile(spawnLocations[spawnChoice].getX()-1,spawnLocations[spawnChoice].getY()+1),
    			new RSTile(spawnLocations[spawnChoice].getX()+1,spawnLocations[spawnChoice].getY()+1)};
    	boxLocations2= new RSTile[]{new RSTile(spawnLocations[spawnChoice].getX()-1,spawnLocations[spawnChoice].getY()-1),
    			new RSTile(spawnLocations[spawnChoice].getX()+1,spawnLocations[spawnChoice].getY()-1),
    			new RSTile(spawnLocations[spawnChoice].getX()-1,spawnLocations[spawnChoice].getY()+1),
    			new RSTile(spawnLocations[spawnChoice].getX()+1,spawnLocations[spawnChoice].getY()+1)};
    }
    /*********************
     * Sets up a box trap
     * @param index
     * @return
     */
    public int setupBox(int index){
    	if(skills.getCurrentSkillLevel(STAT_HUNTER)>=80){
	    	for(int i=0;i<10;++i){
				if((getMyPlayer().getLocation().equals(boxLocations[0]) ||
						getMyPlayer().getLocation().equals(boxLocations[1]) ||
						getMyPlayer().getLocation().equals(boxLocations[2]) ||
						getMyPlayer().getLocation().equals(boxLocations[3]) ||
						getMyPlayer().getLocation().equals(boxLocations[4]))
						&& getObjectAt(getMyPlayer().getLocation())==null){
					charStatus="Setting up a box";
					Inventory=getInventoryArray();
			        for(int j=0;j<Inventory.length;++j){
			        	if(Inventory[j]==boxID){
				        	moveMouse(getInventoryItemPoint(j).x+random(2,10),getInventoryItemPoint(j).y+random(2,10));
				            clickMouse(true);
							return random(100,150);
			        	}
			        }
			        log("Ran out of boxes. Logging out.");
			        stopAllScripts();
				}
				else if(!getMyPlayer().getLocation().equals(boxLocations[index]) && !getMyPlayer().isMoving()){
			    	charStatus="Walking to empty spot";
					atTileTake(boxLocations[index], "Walk");
					wait(random(100,150));
				}
				wait(random(900,1000));
	    	}
    	}
    	else if(skills.getCurrentSkillLevel(STAT_HUNTER)>=63 && skills.getCurrentSkillLevel(STAT_HUNTER)<80){
	    	for(int i=0;i<10;++i){
				if((getMyPlayer().getLocation().equals(boxLocations2[0]) ||
						getMyPlayer().getLocation().equals(boxLocations2[1]) ||
						getMyPlayer().getLocation().equals(boxLocations2[2]) ||
						getMyPlayer().getLocation().equals(boxLocations2[3]))
						&& getObjectAt(getMyPlayer().getLocation())==null){
					charStatus="Setting up a box";
					Inventory=getInventoryArray();
			        for(int j=0;j<Inventory.length;++j){
			        	if(Inventory[j]==boxID){
				        	moveMouse(getInventoryItemPoint(j).x+random(2,10),getInventoryItemPoint(j).y+random(2,10));
				            clickMouse(true);
							return random(100,150);
			        	}
			        }
			        log("Ran out of boxes. Logging out.");
			        stopAllScripts();
				}
				else if(!getMyPlayer().getLocation().equals(boxLocations2[index]) && !getMyPlayer().isMoving()){
			    	charStatus="Walking to empty spot";
					atTileTake(boxLocations2[index], "Walk");
					wait(random(100,150));
				}
				wait(random(900,1000));
	    	}
    	}
        return 0;
    }
    public int loop() {
    	if (!isLoggedIn() || isWelcomeButton()) {
			wait(1000);
            return random(250, 500);
        }
    	ifLost();
    	setCameraAltitude(true);
    	
    	for(int i=0;i<3 && getCurrentTab()!=TAB_INVENTORY; ++i){
            openTab(TAB_INVENTORY);
            wait(random(50,100));
    	}
    	
    	currentLevel=skills.getCurrentSkillLevel(STAT_HUNTER);
    	
    	if(!isIdle())
    		return random(50,100);
    	if(antiBanChins>random(10,20)){
    		if(random(0,2)==1)
    		setCameraRotation(random(0,45));
    		else setCameraRotation(random(315,359));
    		antiBanChins=0;
    	}
    	if(skills.getCurrentSkillLevel(STAT_HUNTER)>=80){
	    	for(int i=0;i<5;++i){
	    		RSItemTile[] itemTile = getGroundItemsAt(boxLocations[i]);
	    		if(itemTile!=null){
	    			for(int k=0;k<itemTile.length;++k){
	    				if(itemTile[k].getItem().getID()==boxID){
	    					charStatus="Picking up box";
	    					atTileTake(boxLocations[i], "Take Box");
	    					return random(150,200);
	    				}
	    			}
	    		}
	    	}
	    	for(int i=0;i<5;++i){//Check each location to see if they have a box or not
	    		tileObjects=getObjectAt(boxLocations[i]);
	    		if(tileObjects!=null && tileObjects.getID()==successfulTrapID && !isInventoryFull()){
	    			charStatus="Picking up Chinchompa";
	    			atTileTake(boxLocations[i], "Check");
	    			return random(150,200);
	    		}
	    	}
	    	for(int i=0;i<5;++i){//Check each location to see if they have a box or not
	    		tileObjects=getObjectAt(boxLocations[i]);
	    		if(tileObjects==null){
	    			return setupBox(i);
	    		}
	    	}
	    	for(int i=0;i<5;++i){//Check each location to see if they have a box or not
	    		tileObjects=getObjectAt(boxLocations[i]);
	    		if(tileObjects.getID()==failedTrapID && !isInventoryFull()){
	    			charStatus="Picking up failed box";
	    			atTileTake(boxLocations[i], "Dismantle");
	    			return random(150,200);
	    		}
	    	}
    	}
    	else if(skills.getCurrentSkillLevel(STAT_HUNTER)>=63 && skills.getCurrentSkillLevel(STAT_HUNTER)<80){
	    	for(int i=0;i<4;++i){
	    		RSItemTile[] itemTile = getGroundItemsAt(boxLocations2[i]);
	    		if(itemTile!=null){
	    			for(int k=0;k<itemTile.length;++k){
	    				if(itemTile[k].getItem().getID()==boxID){
	    					charStatus="Picking up box";
	    					atTileTake(boxLocations2[i], "Take Box");
	    					return random(150,200);
	    				}
	    			}
	    		}
	    	}
	    	for(int i=0;i<4;++i){//Check each location to see if they have a box or not
	    		tileObjects=getObjectAt(boxLocations2[i]);
	    		if(tileObjects!=null && tileObjects.getID()==successfulTrapID && !isInventoryFull()){
	    			charStatus="Picking up Chinchompa";
	    			atTileTake(boxLocations2[i], "Check");
	    			return random(150,200);
	    		}
	    	}
	    	for(int i=0;i<4;++i){//Check each location to see if they have a box or not
	    		tileObjects=getObjectAt(boxLocations2[i]);
	    		if(tileObjects==null){
	    			return setupBox(i);
	    		}
	    	}
	    	for(int i=0;i<4;++i){//Check each location to see if they have a box or not
	    		tileObjects=getObjectAt(boxLocations2[i]);
	    		if(tileObjects.getID()==failedTrapID && !isInventoryFull()){
	    			charStatus="Picking up failed box";
	    			atTileTake(boxLocations2[i], "Dismantle");
	    			return random(150,200);
	    		}
	    	}
    	}
    	if(isIdle()){//Were are just standing there
    		charStatus="Waiting...";
    		return random(10,50);
    	}
    	return random(50,100);
    }
}
